# -*- coding: utf-8 -*-
import sys

def attrs_to_dict(attrs):
    attrdict={}
    for k,v in attrs:
        attrdict[k] = v
    return attrdict
        
class TravianParser():
    def __init__(self, html, autoparse=True):
        from sgmllib import SGMLParser
        self.SGMLParser = SGMLParser
        self.html=html
        if autoparse:
            self.res=self.get_res()
            self.attack=self.dorf1_troop_move()
        
    def __blank(self):
        SGMLParser = self.SGMLParser
        class BlankParser(SGMLParser):
            def reset(self):
                SGMLParser.reset(self)
                self.form = {}
                self.logintag=''
                self.passtag=''
                
    def get_login_fields(self):
        SGMLParser = self.SGMLParser
        class LoginParser(SGMLParser):
            def reset(self):
                SGMLParser.reset(self)
                self.form = {}
                self.logintag=''
                self.passtag=''
                
            def start_input(self, attrs):
                attrs = attrs_to_dict(attrs) 
                if attrs['name']:
                    self.form[attrs['name']] = attrs['value']
                if attrs['type'] == 'text': self.logintag=attrs['name']
                elif attrs['type'] == 'password': self.passtag=attrs['name']
                
        parser = LoginParser()
        parser.feed(self.html)
        parser.close()
        return parser.form, parser.logintag, parser.passtag
        
    def get_res(self):
        SGMLParser = self.SGMLParser
        class ResParser(SGMLParser):
            def reset(self):
                SGMLParser.reset(self)
                self.resid =''
                self.resvalues = {}
                self.resdelta = {}

            def start_td(self, attrs):
                attrs = attrs_to_dict(attrs)
                if attrs.has_key('id'):
                    if attrs['id'] in ('l1','l2','l3','l4'):
                        self.resid=attrs['id']
                        self.resdelta[attrs['id']]=attrs['title']
            
            def end_td(self):
                self.resid=''

            def handle_data(self, text):
                if self.resid in ('l1','l2','l3','l4'):
                    self.resvalues[self.resid]=text
        parser=ResParser()
        parser.feed(self.html)
        parser.close()
        text=(parser.resvalues, parser.resdelta)
        print text
        return parser.resvalues, parser.resdelta

    def dorf1_troop_move(self):
        SGMLParser = self.SGMLParser
        class TroopMoveParser(SGMLParser):
            def reset(self):
                SGMLParser.reset(self)
                self.troop_move_div = False
                self.somebody_attake = False

            def start_img(self, attrs):
                attrs = attrs_to_dict(attrs)
                if attrs.has_key('src'):
                    if attrs['src'] == 'img/un/a/att1.gif':
                        self.somebody_attake = True
 
                                
            def start_div(self, attrs):
                attrs = attrs_to_dict(attrs)
                if attrs.has_key('id'):
                    if attrs['id'] == 'ltbw1':
                        self.troop_move_div = True
                        print 'troop move'

            def end_div(self):
                self.troop_move_div = False

            def start_b(self, attrs):
                attrs = attrs_to_dict(attrs)
                if self.troop_move_div == True:
                    print 'rggg'
                    if attrs.has_key('class'):
                        if attrs['class'] == 'c5 f10':
                            self.somebody_attake = True
                            print "Alarmaaaa!!!!"
        parser=TroopMoveParser()
        parser.feed(self.html)
        parser.close()
        return parser.somebody_attake
                            
                

class TravianBrowser():
    def __init__(self, server, login, password, useragent=None):
        import urllib2, cookielib
        import os.path
        self.urlopen = urllib2.urlopen
        self.Request = urllib2.Request
        self.cj = cookielib.LWPCookieJar()
        self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
        urllib2.install_opener(self.opener)
        self.server = server
        self.login = login
        self.password = password
        self.resolution = '1280:1024'
        if not useragent: useragent = 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9) Gecko/2008061015 Firefox/3.0'
        self.headers = {'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                        'Accept-Language' : 'en-us,en;q=0.5',
                        'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
                        'Keep-Alive' : '300',
                        'Connection' : 'keep-alive',
                        'User-Agent' : useragent,
                        }
        self.refferer = None
        if os.path.isfile(self.server+self.login):
            self.cj.load(self.server+self.login)
        
    def __is_login(self, html):
        loginform='<form method="post" name="snd" action="dorf1.php">'
        if loginform in html:
            return True
        else:
            return False
        
    def __feel_login_form(self, html):
        parser = TravianParser(html, autoparse=False)       
        form, logintag, passtag = parser.get_login_fields()
        form['w']=self.resolution
        form[logintag]=self.login
        form[passtag]=self.password
        form['s1.x']='0'
        form['s1.y']='0'
        #print parser.form['login']
        return form
    
    def fetch_page(self, page, data=None):
        import urllib
        url='http://'+self.server+'/'+page
        try:
            if self.refferer: self.headers[Refferer] = self.refferer
            if data:
                req = self.Request(url, data, self.headers)  # create a request object
            else:
                req = self.Request(url, headers=self.headers)  # create a request object
            handle = self.urlopen(req)                     # and open it to return a handle on the url
        except IOError, e:
            print 'We failed to open "%s".' % url
            if hasattr(e, 'code'):
                print 'We failed with error code - %s.' % e.code
            elif hasattr(e, 'reason'):
                print "The error object has the following 'reason' attribute :"
                print e.reason
                print "This usually means the server doesn't exist,"
                print "is down, or we don't have an internet connection."
            sys.exit()
        else:
            #print 'Here are the headers of the page :'
            #print handle.info()
            #print handle.read() #returns the page
            # print handle.geturl() #returns the true url of the page fetched
            html=handle.read()
            #print self.__is_login(html)
            if self.__is_login(html):
                values=self.__feel_login_form(html)
                data = urllib.urlencode(values)
                self.fetch_page(page, data)
            #print 'These are the cookies we have received so far :'
            #for index, cookie in enumerate(self.cj):
            #    print index, '  :  ', cookie
            self.cj.save(self.server+self.login)
            return html

class TravianMiniAPI:
    def __init__(self):
        pass           
                
if __name__ == '__main__':
    from time import sleep
    TravianVii = TravianBrowser('speed.travian.ru','oxy','oxytrav')
    html = TravianVii.fetch_page('dorf1.php')
    TravianViiParser = TravianParser(html)
    if TravianViiParser.attack:
        print "пора паниковать"
    sleep(5)
#    html = TravianVii.fetch_page('dorf2.php')
#    TravianViiParser = TravianParser(html)
#    TravianAntony = TravianBrowser('s3.travian.ru','Antony','128500')
#    TravianAntony.fetch_page('dorf1.php')
#    TravianAntony.fetch_page('dorf2.php')
    
